package com.nosql.common.util;

import java.io.*;

public class SerializationUtil {
    public static byte[] serialize(Object obj) throws IOException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(obj);
            return bos.toByteArray();
        }
    }

    public static <T> T deserialize(byte[] data, Class<T> clazz)
            throws IOException, ClassNotFoundException {

        try (ByteArrayInputStream bis = new ByteArrayInputStream(data);
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            return clazz.cast(ois.readObject());
        }
    }

    // 在SerializationUtil.java中新增版本控制方法
    public static class VersionAwareObjectOutputStream extends ObjectOutputStream {
        public VersionAwareObjectOutputStream(OutputStream out) throws IOException {
            super(out);
            writeObject(1); // 写入版本号
        }
    }

    public static class VersionAwareObjectInputStream extends ObjectInputStream {
        public VersionAwareObjectInputStream(InputStream in) throws IOException, ClassNotFoundException {
            super(in);
            int version = (int) readObject();
        }
    }

}